import tkinter as tk

class TextRedirector(object):
    def __init__(self, text_widget):
        self.text_widget = text_widget
        self.is_generating_data = False  # 标记是否在输出进度条

    def write(self, str_):
        if "Generating data" in str_:
            if self.is_generating_data:
                # 删除最后一行，准备覆盖
                self.text_widget.delete("end-2l", "end-1l")
            else:
                self.is_generating_data = True

            # 插入新的进度条信息
            self.text_widget.insert(tk.END, str_.strip() + '\n')
        else:
            # 遇到其他正常内容（比如插入完成），重置标志
            self.is_generating_data = False
            self.text_widget.insert(tk.END, str_)

        self.text_widget.see(tk.END)

    def flush(self):
        pass  # tqdm有时会调用flush
